package leetcode.code1074;

import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：131 ms, 在所有 Java 提交中击败了91.51%的用户
//
//内存消耗：41.9 MB, 在所有 Java 提交中击败了62.55%的用户
//
//通过测试用例：40 / 40
public class Solution2 implements IDebug {

	public int numSubmatrixSumTarget(int[][] matrix, int target) {
		int m = matrix.length, n = matrix[0].length;
		int ans = 0;
		for (int l = 0; l < m; l++) {
			int[] cur = new int[n];
			for (int r = l; r < m; r++) {
				for (int k = 0; k < n; k++) {
					cur[k] = cur[k] + matrix[r][k];
				}
				ans += find(cur, target);
			}
		}
		return ans;
	}

	private int find(int[] nums, int target) {
		int ans = 0;
		Map<Integer, Integer> hash = new HashMap<>();
		hash.put(0, 1);
		int sum = 0;
		for (int num : nums) {
			sum += num;
			ans += hash.getOrDefault(sum - target, 0);
			hash.put(sum, hash.getOrDefault(sum, 0) + 1);
		}
		return ans;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(4, this.numSubmatrixSumTarget(HelpDebug.str2array1("[[0,1,0],[1,1,1],[0,1,0]]"), 0));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
